/*
 * PsRecordCasterChannel.h
 *
 *  Created on: 2018年9月1日
 *      Author: zhengboyuan
 */

#ifndef PSRECORDCASTERCHANNEL_H_
#define PSRECORDCASTERCHANNEL_H_

#include "PsRecordCaster.h"
#include "CommandThread.h"
#include "TEvent.h"
#include <vector>
#include "PsCaster.h"

#include "MediaReader.h"
#include "SharedPtr.h"
#include "AVPacketPtr.h"
#include "TimePoint.h"


namespace av
{



class PsRecordCasterChannel : public util::CommandThread
{
public:
	PsRecordCasterChannel();
	virtual ~PsRecordCasterChannel();

	void setID(int id);

	virtual bool open(const PsRecordCasterTransport& transport, MRecord* records, int size, int64_t offset, double scale);

	virtual void close();

	virtual bool addTarget(const char* ip, int port);

	virtual bool removeTarget(const char* ip, int port);

	virtual void removeTargets();

	virtual bool setScale(double scale);

	virtual bool seek(int64_t offset);

	virtual bool startStream();

	virtual void stopStream();

	virtual void pauseStream();

	void setSink(PsRecordCasterSink* sink);

protected:
	virtual void onCommand(Command& cmd);
	virtual void onIdle();

protected:
	typedef std::vector< MRecord >	MRecordArray;

	enum CasterCommandType
	{
		kOpen = 1,
		kClose,

		kPlay,
		kPause,
		kStop,
		kSeek,
		kFlush,

		kSetScale,
	};

protected:
	void sendPacket(AVPacket& pkt);

	void fireMediaEvent(int event, int value);

	void handlePlay();
	void handlePause();
	void handleStop();
	void handleSeek(int64_t offset);
	void handleSetScale(AVRational scale);
	void handleFlush();

	void setState(StreamState state);

	int64_t getClock();
	int computeDelay(AVPacketPtr& pkt);
	void dispatchPacket(AVPacketPtr& pkt);

protected:
	int	m_id;

	PsRecordCasterSink*	m_sink;

	MRecordArray	m_records;
	size_t	m_index;

	pscaster_t	m_caster;

	comn::CriticalSection	m_cs;

	std::shared_ptr<MediaReader>	m_reader;

	StreamState		m_state;
	AVRational	    m_scale;

	TimePoint	m_lastPoint[2];
	int64_t	m_curTime;

};



} /* namespace av */

#endif /* PSRECORDCASTERCHANNEL_H_ */
